<template>
  <div class="setting">
    <!-- 个人中心 -->
    <el-dropdown trigger="click" class="el-dropdown">
      <span class="el-dropdown-link">
        <span class="avatar">
          <img class="img" :src="imgUrl" />
        </span>
        <span>{{ username }}</span>
        <i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item @click.native="goUserinfo">个人中心</el-dropdown-item>
        <el-dropdown-item @click.native="switchingRoleHandle">角色切换</el-dropdown-item>
        <el-dropdown-item @click.native="logoutHandle" v-show="!isGoLogin">退出登录</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
    <!-- 工作状态 1.19版本放开-->
    <el-dropdown style="margin:0 10px;" @command="handleCommand" v-show="false">
      <span class="el-dropdown-link">
        {{workState}}
        <i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item v-for="(item,index) of workStateList" :command="item" :key="index">{{item.name}}</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
    <!-- 角色切换 -->
    <BaseDialog :visible.sync="isShowDialog" title="请您先选择职位" destroyOnClose>
      <div class="wrapScroll">
        <div class="dialogP" style v-for="(item,index) of selectionRole" :key="index" @click="setUserRoleHandle(item)">
          <el-card shadow="hover" :class="(index + 1) % 2 === 0 ? 'cardBackground' : ''">
            <label><span>部门：</span>{{item.orgName}}</label>
            <label><span>角色：</span>{{item.roleName}}</label>
          </el-card>
        </div>
        <div style="text-align: center;margin-top: 30px;">
          <el-button @click="handleClose">返回</el-button>
          <!-- <el-button  type="primary">确定</el-button> -->
        </div>
      </div>
    </BaseDialog>

    <!-- 90天更换密码 -->
    <BaseDialog :closable="false" :visible.sync="editPWT" width="30%" title="修改密码" destroyOnClose>
      <div style="text-align: center;padding-bottom: 30px;">
        <h3 style="line-height: 40px;">您的登陆密码已经超期，请设置新密码（新旧密码不能相同）</h3>
        <FormPanel ref="FormPanel" :cols="1" :list="formList" formType="edit" :isSubmitBtn="false" />
        <p style="padding-bottom:20px;"></p>
        <div :style="{position: 'absolute',
            left: 0,
            bottom: 0,
            right: 0,
            zIndex: 9,
            borderTop: '1px solid #e9e9e9',
            padding: '10px 20px',
            background: '#fff',
            textAlign: 'right'}">
          <el-button @click="cancle">退出登录</el-button>
          <el-button @click="changeHandle" type="primary">确定</el-button>
        </div>
      </div>
    </BaseDialog>
  </div>
</template>

<script>
import { getUser, getToken, removeToken, removeUser, removeDataType, removeAppId, getUserOrgId, setUserOrgId, setToken, setDataType, setAppId, jsEncrypt } from '@/assets/js/auth';
import store from '@/store';
import { authority } from '@/utils/authMixin';
import { mapActions, mapState } from 'vuex';
import * as types from '@/api/login/types';
import { sleep } from '@/utils';
import { doLogin, initLogin, needUpdate, getUserInfo, sendPhoneCode, roleDetail, setUserRole, getInfo, getHeadPortrait, logoutJwt } from '@/api/login/index';

import { testPW } from '@/utils/validate';
import { supereditpassword } from '@/api/common/auth/userInfo/index.js';
import config from '@/assets/js/config';

import Cookies from 'js-cookie';


export default {
  name: 'PersonalCenter',
  mixins: [authority],
  data() {
    return {
      username: getUser(),
      isShowDialog: false,
      selectionRole: [],
      isjwt: '',
      dataType: '',
      editPWT: null,
      formList: this.createFormList(),
      imgUrl: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
      workState: '双皮奶',
      workStateList: [
        { code: 'a', name: '黄金糕' },
        { code: 'b', name: '狮子头' },
        { code: 'c', name: '螺蛳粉' },
        { code: 'd', name: '双皮奶' },
        { code: 'e', name: '蚵仔煎' }
      ],
      isGoLogin: config.isGoLogin
    };
  },
  computed: {
    ...mapState('app', ['btnLoading'])
  },
  async created() {
    // await needUpdate().then(res => {
    //   if (res.resultCode == 200 && res.data == 10041001) {
    //     this.editPWT = true;
    //   } else {
    //     this.editPWT = false;
    //   }
    // });

    getHeadPortrait().then(res => {
      if (res.success) {
        //console.log(res, '图像');
        if (res.data) {
          this.imgUrl = res.data;
        } else {
          this.imgUrl = 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg';
        }
      }
    });
  },
  methods: {
    ...mapActions('app', ['createLoginInfo']),
    //	async logoutJwts (){
    //		console.log(1)
    //		const res = await logoutJwt({
    //			jwt: getToken()
    //		});
    //		console.log(res)
    //	},
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '原密码',
          fieldName: 'password',
          showPassword: true,
          placeholder: '请输入原密码',
          initialValue: '',
          rules: [{ required: true, message: '请输入原密码', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '新密码',
          showPassword: true,
          fieldName: 'newPassword',
          placeholder: '请输入6-32位密码',
          initialValue: '',
          rules: [{ required: true, validator: testPW, trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '确认新密码',
          fieldName: 'confirmPassword',
          showPassword: true,
          placeholder: '确认新密码',
          initialValue: '',
          rules: [{ required: true, validator: testPW, trigger: 'blur' }]
        }
      ];
    },
    // 修改
    async changeHandle(val) {
     // console.log(this.formList, 'this.formList');
      let data = this.$refs.FormPanel.SUBMIT_FORM();
      if (data) {
        if (this.formList.find(x => x.fieldName == 'password').initialValue != this.formList.find(x => x.fieldName == 'newPassword').initialValue) {
          if (this.formList.find(x => x.fieldName == 'newPassword').initialValue != this.formList.find(x => x.fieldName == 'confirmPassword').initialValue) {
            this.$message.error('两次输入密码不一致');
          } else {
            const param = {
              password: this.formList.find(x => x.fieldName == 'password').initialValue,
              newPassword: this.formList.find(x => x.fieldName == 'newPassword').initialValue
            };
            supereditpassword(param)
              .then(res => {
                if (res.resultCode == 200) {
                  // 需要走后台推出接口
                  this.cancle();
                  logoutJwt(getToken()).then(res => {
                    //退出jwt
                    if (res.resultCode === 200) {
                      this.$message({
                        type: 'success',
                        message: '修改成功'
                      });
                      store.dispatch('app/createLogout');
                      removeDataType();
                      removeAppId();
                      this.$router.push({ path: '/login' });
                    }
                  });
                }
              })
              .catch(err => { });
          }
        } else {
          this.$message.error('新旧密码不能一样');
        }
      }
    },
    handleCommand(command) {
      //console.log(command, 'command');
      this.workState = command.name;
    },
    //退出
    cancle() {
      logoutJwt(getToken()).then(res => {
        //退出jwt
        if (res.resultCode === 200) {
          store.dispatch('app/createLogout');
          removeDataType();
          removeAppId();
          this.$router.push({ path: '/login' });
        }
      });
    },
    getCookie() {
      let allCookie = document.cookie.split(';');
      allCookie.forEach(x => {
        if (x.indexOf('jwt') > -1) {
          this.isjwt = x.split('=')[1];
        }
        if (x.indexOf('dataType') > -1) {
          this.dataType = x.split('=')[1];
        }
      });
    },
    goUserinfo() {
      this.$router.push('/admin/auth/userInfo');
    },
    // 角色切换
    switchingRoleHandle() {
      //console.log('角色切换');
      this.getCookie();
      this.isShowDialog = true;
      if (this.isShowDialog) {
        this.selectionRole = [];
        roleDetail()
          .then(res => {
            res.data.forEach(x => {
              this.selectionRole.push(x);
            });
          })
          .catch(err => { });
      }
    },
    // 角色切换后切换菜单
    async setUserRoleHandle(data) {
      if (data) {
        // console.log(data,"item",this.isjwt)
        localStorage.setItem('roleType', data.roleType);
        store.state.app.navList = [];
        // this.$router.go(0)
        // store.dispatch('app/createNavList')
        await setToken(this.isjwt);
        await setUserOrgId(data.userOrgId);
        await setDataType(this.dataType);
        data.jwt = this.isjwt;
        await setUserRole(data).then(res => {
          if (res.resultCode == 200) {
            //console.log(res, '角色切换后切换菜单');
            this.initUserInfo();
          }
        });
      }
    },
    async initUserInfo() {
      //console.log('this.$router', this.$router)

      await initLogin();
      const {
        data: { userInfo }
      } = await getUserInfo();
      this.createLoginInfo({
        id: userInfo.userId,
        name: userInfo.userName
      });
      const userAppId = await getUserInfo();
      if (userAppId.resultCode == 200) {
        //console.log(userAppId, 'userAppId');
        setAppId(userAppId.data.userInfo.appId);
        localStorage.setItem('appId', userAppId.data.userInfo.appId);
      }
      await sleep(100);
      this.handleClose();
      if (this.$router.currentRoute.fullPath === '/home') {
        window.location.reload();
      } else {
        window.location.replace(`${window.location.origin}/home`);
      }

      // this.$router.go(0);
      // redirect
    },
    //关闭角色切换
    handleClose() {
      this.isShowDialog = false;
    },
    async logoutHandle() {
      // 需要走后台推出接口
      const res = await logoutJwt(getToken());
      window.__GEEGAGUC__.logout(config.gucUrl);

    }
  }
};
</script>

<style lang="less" scoped>
.setting {
  margin-left: 8px;
  .el-dropdown {
    .el-dropdown-link {
      padding: 6px 0;
      font-size: @textSize;
      cursor: pointer;
      .avatar {
        display: inline-block;
        overflow: hidden;
        width: 24px;
        height: 24px;
        border-radius: @borderRadius;
        vertical-align: middle;
        .img {
          object-fit: cover;
          display: block;
          height: 100%;
        }
      }
    }
  }
}

.wrapScroll {
  max-height: 300px;
  overflow-y: scroll;
}
.dialogP {
  font-size: 17px;
  line-height: 50px;
  padding-left: 10px;
  a {
    display: block;
    h3 {
      color: #666;
      font-weight: 900;
    }
    p {
      height: 26px;
      line-height: 20px;
      font-size: 14px;
      margin-left: 10px;
    }
  }
}
.el-card {
  width: 97%;
  margin: 10px auto 10px;
  color: #606266;
  font-size: 14px;
  letter-spacing: 0.5px;
  cursor: pointer;
  &.cardBackground {
    background: rgb(244, 244, 245);
  }
  &:hover {
    background: rgb(198, 226, 255);
    color: #000;
    cursor: pointer;
  }
  .el-card__body {
    width: 100%;
    cursor: pointer;
    box-sizing: border-box;
    line-height: 20px;
    label {
      width: 100%;
      cursor: pointer;
      box-sizing: border-box;
      padding: 0 5px 0 5px;
      display: block;
      line-height: 30px;
      span {
        font-weight: bold;
      }
    }
  }
}
</style>
